//
// Created by jiang on 2021/12/15.
//

#include "pwm.h"
#include "tim.h"
#include "string.h"
#include "motor.h"

pwm_t pwm;

inline void PWM_Init(pwm_t *pHandle) {
    memset(pHandle->cmpVal, 0, sizeof(pHandle->cmpVal));
}

void PWM_EnableOutput(pwm_t *pHandle) {
    __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
    HAL_TIM_Base_Start(&htim1);

    pHandle->cmpVal[0] = PWM_HALF_PERIOD_COUNT;
    pHandle->cmpVal[1] = PWM_HALF_PERIOD_COUNT;
    pHandle->cmpVal[2] = PWM_HALF_PERIOD_COUNT;

    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pHandle->cmpVal[0]);
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_2, pHandle->cmpVal[1]);
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_3, pHandle->cmpVal[2]);

    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
    HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1);
    HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_2);
    HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_3);
}

void PWM_DisableOutput(pwm_t *pHandle) {
    HAL_TIM_Base_Stop(&htim1);
    __HAL_TIM_DISABLE_IT(&htim1, TIM_IT_UPDATE);

    pHandle->cmpVal[0] = PWM_HALF_PERIOD_COUNT;
    pHandle->cmpVal[1] = PWM_HALF_PERIOD_COUNT;
    pHandle->cmpVal[2] = PWM_HALF_PERIOD_COUNT;

    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pHandle->cmpVal[0]);
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_2, pHandle->cmpVal[1]);
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_3, pHandle->cmpVal[2]);

    HAL_TIM_PWM_Stop(&htim1, TIM_CHANNEL_1);
    HAL_TIM_PWM_Stop(&htim1, TIM_CHANNEL_2);
    HAL_TIM_PWM_Stop(&htim1, TIM_CHANNEL_3);
    HAL_TIMEx_PWMN_Stop(&htim1, TIM_CHANNEL_1);
    HAL_TIMEx_PWMN_Stop(&htim1, TIM_CHANNEL_2);
    HAL_TIMEx_PWMN_Stop(&htim1, TIM_CHANNEL_3);
}


void PWM_EnableTrigger(pwm_t *pHandle) {
    pHandle->cmpVal[3] = PWM_PERIOD_COUNT - 10;
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, pHandle->cmpVal[3]);

    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_4);
    HAL_TIM_Base_Start(&htim1);
}


void PWM_SetCompare(pwm_t *pHandle, abc_t *t) {
    pHandle->cmpVal[0] = (uint16_t)((t->a * PWM_PERIOD_COUNT) / 1000);
    pHandle->cmpVal[1] = (uint16_t)((t->b * PWM_PERIOD_COUNT) / 1000);
    pHandle->cmpVal[2] = (uint16_t)((t->c * PWM_PERIOD_COUNT) / 1000);

    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pHandle->cmpVal[0]);
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_2, pHandle->cmpVal[1]);
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_3, pHandle->cmpVal[2]);
}


void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim == &htim1){
        MOTO_Process(&motor);
    }
}

